package com.mai4j.maiadmin.service.impl;

import com.mai4j.maiadmin.model.dto.CurrencyDescriptionDTO;
import com.mai4j.maiadmin.service.CurrencyDescriptionService;
import com.mai4j.maiadmin.support.JooqProvider;
import com.mai4j.maiadmin.support.cache.CacheName;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.mai4j.maiadmin.generated.Tables.CURRENCY_DESCRIPTION;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Service
public class CurrencyDescriptionServiceImpl implements CurrencyDescriptionService {

    /**
     * @param currencyId currencyId
     * @return CurrencyDescriptionDTOS
     */
    @Cacheable(value = CacheName.DATA, key = "'currency:description:' + #currencyId")
    @Override
    public List<CurrencyDescriptionDTO> get(Long currencyId) {
        return JooqProvider.dsl().selectFrom(CURRENCY_DESCRIPTION)
                .where(CURRENCY_DESCRIPTION.CURRENCY_ID.eq(currencyId))
                .fetchInto(CurrencyDescriptionDTO.class);
    }

    @CacheEvict(value = CacheName.DATA, key = "'currency:description:' + #currencyId")
    @Override
    public void saveDescriptions(Long currencyId, List<CurrencyDescriptionDTO> descriptions) {
        JooqProvider.dsl()
                .deleteFrom(CURRENCY_DESCRIPTION)
                .where(CURRENCY_DESCRIPTION.CURRENCY_ID.eq(currencyId))
                .execute();
        for (CurrencyDescriptionDTO descriptionDTO : descriptions) {
            JooqProvider.dsl().insertInto(CURRENCY_DESCRIPTION)
                    .columns(
                            CURRENCY_DESCRIPTION.CURRENCY_ID,
                            CURRENCY_DESCRIPTION.LANGUAGE_CODE,
                            CURRENCY_DESCRIPTION.NAME
                    )
                    .values(currencyId,
                            descriptionDTO.getLanguageCode(),
                            descriptionDTO.getName())
                    .execute();
        }
    }

    @CacheEvict(value = CacheName.DATA, key = "'currency:description:' + #currencyId")
    @Override
    public void delete(Long currencyId) {
        JooqProvider.dsl()
                .deleteFrom(CURRENCY_DESCRIPTION)
                .where(CURRENCY_DESCRIPTION.CURRENCY_ID.eq(currencyId))
                .execute();
    }
}
